package com.dd.ent.car.ui.user;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.dd.ent.car.R;
import com.dd.ent.car.common.bean.User;
import com.dd.ent.car.common.config.UIConfig;
import com.dd.ent.car.service.user.UserService;
import com.dd.ent.car.ui.BaseActivity;
import com.pp.ent.core.manage.UIHandler;
import com.pp.ent.view.annotation.ContentView;
import com.pp.ent.view.annotation.Inject;
import com.pp.ent.view.annotation.ViewInject;

import cn.smssdk.SMSSDK;

import static android.widget.Toast.LENGTH_LONG;


/**
 * Created by dengqu on 2016/5/30.
 *
 * @author dengqu
 */
@ContentView(R.layout.activity_login_layout)
public class LoginActivity extends BaseActivity {
    private static final String TAG = LoginActivity.class.getSimpleName();
    public static final String TYPE = "type";
    public static final String PHONE_NUMBER = "phone_number";
    @ViewInject(R.id.et_phone_num)
    private EditText mEtPhoneNum;
    @ViewInject(R.id.et_register_password)
    private EditText mEtRegisterPassword;
    @ViewInject(R.id.iv_icon_mobile)
    private ImageView mIvPhone;
    @ViewInject(R.id.iv_icon_password)
    private ImageView mIvPassword;
    @ViewInject(R.id.btn_submit)
    private View mBtnSubmit;
    @ViewInject(R.id.tv_register)
    private TextView mTvRegister;
    @ViewInject(R.id.tex_forget_password)
    private TextView mTvForgetPassword;
    @Inject
    private UserService userService;
    private ProgressDialog mProgressDialog;
    private String mPhoneNumber;

    public static void startActivity(Context context) {
        Intent intent = new Intent(context, LoginActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        mPhoneNumber = intent.getStringExtra(PHONE_NUMBER);
        init();
    }

    private void init() {
        addListener();
    }

    private void addListener() {
        mBtnSubmit.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                submitBtnOnClick(v);
            }
        });
        mEtPhoneNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                changeButtonEnableState();
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });
        mEtPhoneNum.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                mIvPhone.setImageDrawable(getResources().getDrawable(hasFocus ? R.drawable.icon_mobile_focused : R.drawable.icon_mobile));
            }
        });
        mEtRegisterPassword.setOnFocusChangeListener(new OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                mIvPassword.setImageDrawable(getResources().getDrawable(hasFocus ? R.drawable.icon_password_focused : R.drawable.icon_password));
            }
        });

        mTvRegister.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                RegesiterActivity.startActivity(LoginActivity.this, 0);
            }
        });
        mTvForgetPassword.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                FindPasswordActivity.startSlef(LoginActivity.this);

            }
        });
        findViewById(R.id.titlebar_left).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void submitBtnOnClick(View v) {
        hiddenInput(v);
        if (isCorrectNumber()) {
            submitOnClick();
        } else {
            dismissProgressDialog();
        }
    }

    protected void submitOnClick() {
        showProgressDialog(R.string.loading);
        login();
    }

    private void login() {
        String phoneNumber = getPhoneNumber();
        String password = mEtRegisterPassword.getText().toString();
        userService.login(phoneNumber, password);

    }

    @NonNull
    protected String getPhoneNumber() {
        return mEtPhoneNum.getText().toString();
    }

    @Override
    protected void onResume() {
        super.onResume();
        changeButtonEnableState();
    }

    @Override
    protected void onStop() {
        super.onStop();
        dismissProgressDialog();
    }

    protected void onDestroy() {
        super.onDestroy();
    }

    protected void showErrorTip(String msg) {
        dismissProgressDialog();
        Toast.makeText(this, msg, LENGTH_LONG).show();
    }

    protected void dismissProgressDialog() {
        if (null != mProgressDialog) {
            mProgressDialog.dismiss();
            mProgressDialog = null;
        }
    }

    protected void showProgressDialog(int message) {
        dismissProgressDialog();
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        mProgressDialog.setMessage(getResources().getString(message));
        mProgressDialog.setCancelable(false);
        mProgressDialog.show();
    }

    private boolean isCorrectNumber() {
        String number = getPhoneNumber();
        if (TextUtils.isEmpty(number)) {// 手机号没输入
            showErrorTip(getString(R.string.register_please_input_phone_number));
            return false;
        } else if (!number.matches("^1[0-9]{10}$")) {// 手机号不符合
            showErrorTip(getString(R.string.register_please_input_correct_phone_number));
            return false;
        } else {
            return true;
        }
    }

    private void hiddenInput(View v) {
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), 0);
    }

    /**
     * 设置按钮是否可以点击的状态
     */
    private void changeButtonEnableState() {
        if (mEtPhoneNum.getText().length() > 0) {
            mBtnSubmit.setEnabled(true);
        } else {
            mBtnSubmit.setEnabled(false);
        }
    }

    @UIHandler(UIConfig.PHONE_NUMBER_LOGIN_SUCCESS)
    public void phoneNumberRegisteSuccessResponse(User user) {
        finish();
    }

    @UIHandler(UIConfig.PHONE_NUMBER_REGISTER_SUCCESS)
    public void phoneNumberRegisteResponse(User user) {
        finish();
    }

    @UIHandler(UIConfig.PHONE_NUMBER_LOGIN_FAIL)
    public void phoneNumberRegisteFailResponse() {
        showErrorTip("登录失败，手机或者密码不正确!");
    }
}
